<template>
  <div class="user-management-container">
    <a-card class="section-card">
      <div class="table-toolbar">
        <div class="left">
          <a-input-search
            v-model:value="searchParams.searchText"
            placeholder="搜索科目/职责"
            style="width: 250px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="searchParams.status"
            placeholder="状态筛选"
            style="width: 150px; margin-left: 16px"
            allowClear
            @change="handleSearch"
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="2">禁用</a-select-option>
          </a-select>
        </div>
        <div class="right">
          <a-button type="primary" @click="showAddModal"> <PlusOutlined /> 添加提示词 </a-button>
          <a-button
            style="margin-left: 8px"
            @click="handleBatchDelete"
            :disabled="selectedRowKeys.length === 0"
          >
            <delete-outlined /> 批量删除
          </a-button>
          <a-button style="margin-left: 8px" @click="handleSearch">
            <reload-outlined /> 刷新
          </a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <span>{{ record.id }}</span>
          </template>
          <template v-if="column.key === 'status'">
            <a-badge
              :status="record.status === 1 ? 'success' : 'default'"
              :text="record.status === 1 ? '正常' : '禁用'"
            />
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="() => handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="() => handleToggleStatus(record)">{{ record.status === 1 ? '禁用' : '启用' }}</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="Are you sure delete this task?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="() => handleDelete(record)"
                @cancel="cancel"
              >
                <a >删除</a>
              </a-popconfirm>

            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑提示词模态框 -->
    <a-modal
      v-model:open="promptModalVisible"
      :title="isEditing ? '编辑提示词' : '添加提示词'"
      @ok="handleUserModalOk"
      @cancel="handleUserModalCancel"
      width="600px"
    >
      <a-form :model="promptForm" :rules="promptFormRules"  layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="subject" label="科目">
              <a-input
                v-model:value="promptForm.subject"
                placeholder="请输入科目"
                :disabled="isEditing"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="role" label="职责">
              <a-input v-model:value="promptForm.role" placeholder="请输入职责" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item name="effect" label="作用">
              <a-input v-model:value="promptForm.effect" placeholder="请输入作用" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="status" label="状态">
              <a-select v-model:value="promptForm.status" placeholder="请选择状态">
                <a-select-option value="active">正常</a-select-option>
                <a-select-option value="inactive">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item name="content" label="内容">
          <a-textarea v-model:value="promptForm.content" :rows="6" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  PlusOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { addPromptSelf, deletePromptSelf, listPromptSelfByPage, updatePromptSelf } from '@/api/promptSelfController'
// 表格列定义
const columns = [
  {
    title: '#',
    key: 'id',
    width: 60,
  },
  {
    title: '科目',
    dataIndex: 'subject',
    key: 'subject',
  },
  {
    title: '职责',
    dataIndex: 'role',
    key: 'role',
  },
  {
    title: '作用',
    dataIndex: 'effect',
    key: 'effect',
    sorter: true,
  },
  {
    title: '内容',
    dataIndex: 'content',
    key: 'content',
    width: 100,
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
    filters: [
      { text: '正常', value: 1 },
      { text: '禁用', value: 1 },
    ],
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true,
    width: 170,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]
const searchParams = reactive<API.PromptSelfQueryRequest>({
  current: 1,
  pageSize: 10,
})
const total = ref(0)
const dataList = ref<API.PromptSelf[]>([])
const fetchData = async () => {
  const res = await listPromptSelfByPage({
    ...searchParams,
  })
  if (res.data.data && res.data.code === 0) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败' + res.data.msg)
  }
}
onMounted(() => {
  fetchData()
})

// 表格加载状态
const loading = ref(false)

// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1, //有则按照传过来的，否则默认为1
    pageSize: searchParams.pageSize ?? 10, //默认为 10
    total: Number(total.value) ?? 0, //默认为 0
    showSizeChanger: true,
    showTotal: (total) => `共${total}条数据`,
  }
})

// 选中的行
const selectedRowKeys = ref<string[]>([])

// 提示词表单相关
const promptModalVisible = ref(false)
const isEditing = ref(false)
const promptForm = reactive<API.PromptSelfAddRequest>({
  id:'',
  subject:'',
  role:'',
  effect:'',
  content:'',
  status:1
})

// 表单验证规则
const promptFormRules = {
  subject: [
    { required: true, message: '请输入科目', trigger: 'blur' },
    { min: 3, max: 20, message: '科目长度为3-20个字符', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请输入职责', trigger: 'blur' }],
  effect: [
    { required: true, message: '请输入作用', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  content: [
    { required: false, message: '请输入内容', trigger: 'blur' },],
}

// 表格选择变更
const onSelectChange = (keys: string[]) => {
  selectedRowKeys.value = keys
}

// 处理表格变更（排序、筛选等）
const handleTableChange = (page: any, filters: any, sorter: any) => {
  loading.value = true
  // 更新分页
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
  loading.value = false
}

// 搜索
const handleSearch = (value: string) => {
  loading.value = true
  fetchData()
  loading.value = false
  pagination.value.current = 1
}

// 显示添加模态框
const showAddModal = () => {
  isEditing.value = false
  promptModalVisible.value = true
}

// 处理编辑
const handleEdit = async (record: any) => {
  isEditing.value = true
  //获取原来的数据
      Object.keys(promptForm).forEach(k => {
        if (k in record) promptForm[k] = record[k];
      });
  promptModalVisible.value = true
}

// 处理提示词模态框确认
const handleUserModalOk = async () => {
  try {
    let res = null
    if (!isEditing.value) {
      //不是编辑，即add
      res = await addPromptSelf({
        ...promptForm,
      })
    } else {
      res = await updatePromptSelf({
        ...promptForm,
      })
    }
    if (res.data.data && res.data.code === 0) {
      message.success(isEditing.value ? '提示词更新成功' : '提示词添加成功')
      await fetchData()
    } else {
      message.error(isEditing.value ? '提示词更新失败' : '提示词添加失败')
    }
  } catch (e) {
    message.error(isEditing.value ? '提示词更新失败' : '提示词添加失败')
  }
  promptModalVisible.value = false
}

// 处理提示词模态框取消
const handleUserModalCancel = () => {
  promptModalVisible.value = false
}
// 处理切换状态
const handleToggleStatus = async (record: any) => {
  const newStatus = record.status === 1 ? 2 : 1
  console.log(newStatus)
  try {
    const res = await updatePromptSelf({
      id: record.id,
      status: newStatus,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已${newStatus === 1 ? '启用' : '禁用'}提示词 ${record.role}`)
    } else {
      message.error(`${newStatus === 1 ? '启用' : '禁用'}提示词 ${record.role}失败`)
    }
  } catch (e) {
    message.error(`已${newStatus === 1 ? '启用' : '禁用'}提示词 ${record.role}失败`)
  }
}
// 处理删除
const handleDelete = async (record: any) => {
  try {
    const res = await deletePromptSelf({
      id: record.id,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已删除提示词 ${record.role}`)
    } else {
      message.error(`删除提示词 ${record.role}失败`)
    }
  } catch (e) {
    message.error(`删除提示词 ${record.role}失败`)
  }
}
const cancel = (e: MouseEvent) => {

};
// 处理批量删除 TODO
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) return
  console.log(selectedRowKeys.value)
  // 实际项目中这里会调用API批量删除提示词
  message.success(`已删除 ${selectedRowKeys.value.length} 个提示词`)
  selectedRowKeys.value = []
}
</script>

<style scoped>
.user-management-container {
  padding-bottom: 40px;
  padding-top: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 24px;
  color: var(--primary-color);
}

.section-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left,
.right {
  display: flex;
  align-items: center;
}
</style>
